const axios = require('axios');

async function testFrontendUpdate() {
  try {
    // 登录获取令牌
    console.log('0. 登录获取令牌...');
    const loginResponse = await axios.post('http://localhost:3000/api/auth/login', {
      username: 'admin',
      password: '123456'
    });
    
    if (loginResponse.data.status !== 'success') {
      console.log('登录失败:', loginResponse.data.message);
      return;
    }
    
    const token = loginResponse.data.token;
    console.log('登录成功，获取到令牌');
    
    // 设置后续请求的认证头
    const authHeader = { Authorization: `Bearer ${token}` };
    
    // 第一步：获取仓库列表
    console.log('\n1. 获取仓库列表...');
    const listResponse = await axios.get('http://localhost:3000/api/inventory/warehouses', {
      headers: authHeader
    });
    console.log(`获取到 ${listResponse.data.data.length} 个仓库`);
    
    if (listResponse.data.data.length === 0) {
      console.log('没有找到任何仓库，请先创建仓库');
      return;
    }
    
    // 获取第一个仓库
    const warehouse = listResponse.data.data[0];
    console.log('选择仓库:', warehouse);
    
    // 第二步：获取仓库详情
    console.log(`\n2. 获取仓库ID=${warehouse.id}的详情...`);
    const detailResponse = await axios.get(`http://localhost:3000/api/inventory/warehouses/${warehouse.id}`, {
      headers: authHeader
    });
    console.log('仓库详情:', detailResponse.data);
    
    // 第三步：更新仓库信息
    console.log('\n3. 发送更新请求...');
    
    // 构造更新数据，与前端表单一致
    const updateData = {
      name: '国贸店', 
      location: '公司总部',
      contact: '123456789',
      status: true,  // 将数字1改为布尔值true
      remarks: '主要仓库'
    };
    console.log('更新数据:', updateData);
    
    // 发送更新请求
    const updateResponse = await axios.put(
      `http://localhost:3000/api/inventory/warehouses/${warehouse.id}`,
      updateData,
      { headers: authHeader }
    );
    
    console.log('更新响应:', updateResponse.data);
    
    if (updateResponse.data.success) {
      console.log('仓库更新成功！');
    } else {
      console.log('仓库更新失败:', updateResponse.data.message);
    }
  } catch (error) {
    console.error('测试失败:', error.message);
    if (error.response) {
      console.error('错误响应:', error.response.data);
    }
  }
}

testFrontendUpdate(); 